var duang = duang || {};

duang.op = $.extend({}, {
	'domain': "",		//项目
	'debug': true,
	'mobileWidth': 768,
	'searchStatus': null	//查询状态
}, appConfig);

//ajax get请求
duang.get = function(url, data, callback, type){
	duang.loading();
	if(typeof(data) == "function"){
		$.get(duang.op.domain+url, function(d){
			duang.closeLoading();
			if(data) data(d);
		}, type || 'json');
	}else{
		$.get(duang.op.domain+url, data, function(d){
			duang.closeLoading();
			if(callback) callback(d);
		}, type || 'json');
	}
	
}

//ajax post请求
duang.post = function(url, data, callback, type){
	duang.loading();
	if(typeof(data) == "function"){

		$.ajax({
			type: 'POST',
			url: duang.op.domain+url,
			dataType: 'json',
			success: function(d){
				//根据约定特殊处理请求结果
				if(!d || !d.HedaACK || !d.HedaACK.Body){
					d = $.extend(true, d, {
						HedaACK: {
							Body:{
								retCode: -1,
								retMsg: '服务链接异常，请检查网络或服务器。'
							}
						}
					});
				}
				console.log("请求结果：", d);
				duang.closeLoading();
				if(d && !d.HedaACK){
					location.href = "login.html";
				}
				if(data) data(d);
			},
			error: function(e){
				duang.closeLoading();
				console.log("error: ", e);
				duang.alert('danger', '服务链接异常，请检查网络或服务器。');
			}
		});
	}else{

		$.ajax({
			type: 'POST',
			url: duang.op.domain+url,
			dataType: 'json',
			data: data,
			success: function(d){
				//根据约定特殊处理请求结果
				if(!d || !d.HedaACK || !d.HedaACK.Body){
					d = $.extend(true, d, {
						HedaACK: {
							Body:{
								retCode: -1,
								retMsg: '服务链接异常，请检查网络或服务器。'
							}
						}
					});
				}
				console.log("请求结果：", d);
				duang.closeLoading();
				if(d && !d.HedaACK){
					location.href = "login.html";
				}
				if(callback) callback(d);
			},
			error: function(e){
				duang.closeLoading();
				console.log("error: ", e);
				duang.alert('danger', '服务链接异常，请检查网络或服务器。');
			}
		});
	}
}

//弹出html
duang.html = function(title, html, width, height, success){
	width = duang.checkMobile()? "auto": (width || "auto");
	height = height || "auto";
	return layer.open({
		type: 1,
		area: [width, height],//宽高
		title: title,
		content: html,
		success: function(layero, index){
	        if(success) success(layero, index);
	    }
	});
}

//确认取消弹窗
duang.confirm = function(msg, yesBack, noBack){
	msg = msg || "确认操作吗？";
	var confirmIndex = layer.confirm(msg, {
	    btn: ['确定','取消'], //按钮
	    shade: 0.5,
	    icon: 0,
	    scrollbar: true
	}, function(){
	    if(yesBack) yesBack();
	    layer.close(confirmIndex);
	}, function(){
		if(noBack) noBack();
	});
	return confirmIndex;
}

//消息弹窗
duang.alert = function(type, msg, yesBack){
	type = type || "success";
	var shift = 0;
	switch(type){
	case "success":
		type = 1;
		msg = msg || "操作成功";
		break;
	case "error":
	case "danger":
		type = 2;
		shift = 6;
		msg = msg || "操作失败";
		break;
	case "warning":
		type = 0;
		msg = msg || "操作警告";
		break;
	}
	var alertIndex = layer.alert(msg, {
	    icon: type,
	    shift: shift
	}, function(){
		if(yesBack) yesBack();
		layer.close(alertIndex);
	});
}

//loading 遮罩层
var loadingIndex, loadingTimer, isLoading = false;
duang.loading = function(){
	// console.log("loadingIndex", loadingIndex)
	if(!isLoading){
		isLoading = true;
		loadingTimer = setTimeout(function(){
			loadingIndex = layer.open({
				type: 3,
				title: false,
				shade: [0.1]
			});
		}, 200);
	}
}
//关闭loading 遮罩层
duang.closeLoading = function(){
	clearTimeout(loadingTimer);
	layer.close(loadingIndex);
	isLoading = false;
}

//无title的消息提示
duang.msg = function(type, msg, yesBack){
	if(typeof(type) == "boolean"){
		type = type?"success":"danger";
	}
	type = type || "success";
	shift = 1;
	switch(type){
	case "success":
		type = 1;
		msg = msg || "操作成功";
		break;
	case "danger":
		type = 2;
		shift = 6;
		msg = msg || "操作失败";
		break;
	case "warning":
		type = 0;
		shift = 6;
		msg = msg || "操作警告";
		break;
	}
	return layer.msg(msg,{icon: type, shift: shift, zIndex:19891110, offset: '20px'}, yesBack);
}

//iframe弹窗
duang.iframe = function(title, url, width, height, yesBack, noBack){
	width = duang.checkMobile()? "auto": (width || "auto");
	height = height || "auto";
	var conf = {
		type: 2,
	    shade: 0.8,
	    fix: false, //不固定
	    area: [width, height],
	    maxmin: true,
	    title: title,
	    content: url,
	    moveOut: true,
	    success:function(layero, index){
			if(yesBack) yesBack({});
	    	//layer.iframeAuto(index);
	    },
	    cancel: function(index){
	    	if(noBack) noBack();
	    }
	};
	if(!yesBack) delete conf.btn;
	return layer.open(conf);
}

//关闭指定弹窗,如果不传参，则关闭所有，乳沟传的是字符串，则按类型关闭
duang.close = function(index){
	if(index == null){
		layer.closeAll();
	}else if(typeof(index) == "string"){
		layer.closeAll(index);
	}else{
		layer.close(index);
	}
}

duang.result = function(msg, infoList, listUrl, addUrl){
	var data = {
		msg: msg,
		infoList: infoList,
		listUrl: listUrl,
		addUrl: addUrl
	}
	location.href = "zygl_ptgl_tianjiajieguo.html?"+duang.parseParam(data);
}

//对外暴露layer对象，统一调用，也可以直接调用layer
duang.layer = layer;

//HTML5 本地存储=========================================
//存储值
duang.setData = function(key, value){
	var temp = duang._getLSData();
	temp[key] = value;
	store.set(duang.op.storageKey, temp);
}
//获取值
duang.getData = function(key){
	var temp = duang._getLSData();
	return temp[key];
}
//清空缓存
duang.clearData = function(key){
	if(key){
		var temp = duang._getLSData();
		delete temp[key];
		duang.setData(key, temp);
	}else{
		store.clear();
	}
}
//H5 本地存储 工具类=====
//获取本地存储顶级对象
duang._getLSData = function(){
	return store.get(duang.op.storageKey) || {};
}


/*********************************************************************
* 工具方法
**********************************************************************/
//json转数组
duang.jsonToArray = function(json){
	var array = [];
	for(var key in json){
		array.push(json[key]);
	}
	return array;
}
//判断是否是手机端（靠宽度判断）
duang.checkMobile = function(){
	var ww = $(window).width();
	return ww <= duang.op.mobileWidth;
}
//获取url查询参数，返回对象数组
duang.getLocationSearch = function(){
	var search = window.location.search;
	var searchJson = {};
	if(search){
		search = search.substring(1);
		var items = search.split("&");
		for(var item in items){
			var temp = items[item].split("=");
			if(searchJson[temp[0]]){
				var tempList = searchJson[temp[0]] || [];
				if(typeof tempList === "string"){
					tempList = [];
					tempList.push(searchJson[temp[0]]);
				}else{
					tempList.push(decodeURIComponent(temp[1]));
				}
				searchJson[temp[0]] = tempList;
			}else{
				searchJson[temp[0]] = decodeURIComponent(temp[1]);
			}
		}
	}
	if(duang.op.searchStatus){
		var items = duang.op.searchStatus.split("&");
		for(var item in items){
			var temp = items[item].split("=");
			searchJson[temp[0]] = decodeURI(temp[1]);
		}
	}
	return searchJson;
}

//引入css
duang.importCss = function(filePath){
	var fileref = document.createElement('link');
	fileref.setAttribute("rel", "stylesheet");
	fileref.setAttribute("type", "text/css");
	fileref.setAttribute("href", filePath);
	if (typeof fileref != "undefined") {
		document.getElementsByTagName("head")[0].appendChild(fileref);
	}
}
//引入js
duang.importJS = function(filePath){
	var fileref = document.createElement('script');
	fileref.setAttribute("src", filePath);
	if (typeof fileref != "undefined") {
		document.getElementsByTagName("head")[0].appendChild(fileref);
	}
}
//调整css
duang.iframeResponsive = function(){
	var obj = $(".embed-responsive");
	if(obj.length > 0){
		var contentHeight = $(".content-wrapper").height();
		var headerHeight = $(".content-header").height();
		var footerHeight = $(".main-footer").height();
		var panelHeight = contentHeight - headerHeight-footerHeight-30;
		obj.css("padding-bottom", (panelHeight)+"px");
	}
}
/**
 * 把json对象转成get请求的参数字符串
 * @param param	json对象
 * @param key	可省略，最外层的key
 * @returns {string}
 */
duang.parseParam = function (param, key) {
	var paramStr = "";
	if (param instanceof String || param instanceof Number || param instanceof Boolean) {
		paramStr += "&" + key + "=" + encodeURIComponent(param);
	}
	else {
		$.each(param, function (i) {
			var k = key == null ? i : key + (param instanceof Array ? "" : "." + i);
			paramStr += '&' + duang.parseParam(this, k);
		});
	}
	return paramStr.substr(1);
};

duang.include = function(url){
	$.ajax({
		async: false,
		dataType: 'html',
		type: 'GET',
		url: url,
		success: function(html){
			document.write(html);
		},
		error: function(e){
			console.log('include error', e);
		}
	});
};

;(function($){
	//把表单对象换成json对象
    $.fn.serializeJson=function(){
        var serializeObj={};
        var array=this.serializeArray();
        var str=this.serialize();
        $(array).each(function(){
            if(serializeObj[this.name]){
                if($.isArray(serializeObj[this.name])){
                    serializeObj[this.name].push(this.value);
                }else{
                    serializeObj[this.name]=[serializeObj[this.name],this.value];
                }
            }else{
                serializeObj[this.name]=this.value; 
            }
        });
        return serializeObj;
    };

    //自动转换表单为json对象，并支持直接合并
    $.fn.autoData = function(param){
    	var json = this.serializeJson();
    	var data = $.extend(true, json, param);
    	return data;
    }

    ////自动转换表单为json对象字符串，并支持直接合并
    $.fn.autoDataStr = function(param){
    	var data = this.autoData(param);
    	return JSON.stringify(data);
    }
})(jQuery);
